<?php
/**
 * Created by PhpStorm.
 * User: TC
 * Date: 2015/10/22
 * Time: 17:09
 */
//include dirname(__FILE__) . '/../libs/controller/peopleController.php';
//include dirname(__FILE__) . '/../libs/config.php';
date_default_timezone_set("PRC");

Router();

function Router() {
    $reqType = $_SERVER["REQUEST_METHOD"];
    var_dump($reqType);
    switch($reqType) {
        case "GET" :
            GetPeoples();
            break;
        case "POST" :
            AddPeople();
            break;
        default :
            var_dump(6404);
            return ;
    }
}

function AddPeople() {
    var_dump('add');
    $name = isset($_POST['name']) ? $_POST['name'] : '';
    $age = isset($_POST['age']) ? $_POST['age'] : '';
    $school = isset($_POST['school']) ? $_POST['school'] : '';
    $address = isset($_POST['address']) ? $_POST['address'] : '';
    $dbname = 'test';
    $host = '127.0.0.1';
    $port = 27017;
    $userName = 'tc';
    $pwd = 'tc199286196988';
    $people = array(
        "name" => $name,
        "age" => new MongoInt32($age),
        "school" => $school,
        "address" => $address,
        "createAt" => new MongoDate(time())
    );
    try {
        $mongoClient = new MongoClient("mongodb://$host:$port");
        $mongoDB = $mongoClient->selectDB($dbname);
        $mongoDB->authenticate($userName, $pwd);
        $peopleCollection = $mongoDB->selectCollection("peoples");
        $result = $peopleCollection->save($people);
        echo json_encode(array("code" => 6200, "data" => $people));
    } catch(MongoConnectionException $e) {
        echo json_encode(array("code" => 6400));
    }
}

function GetPeoples() {
    var_dump('getpeople');
    $dbname = 'test';
    $host = '127.0.0.1';
    $port = 27017;
    $userName = 'tc';
    $pwd = 'tc199286196988';
    try {
        $mongoClient = new MongoClient("mongodb://$host:$port");
        $mongoDB = $mongoClient->selectDB($dbname);
        $mongoDB->authenticate($userName, $pwd);
        $peopleCollection = $mongoDB->selectCollection("peoples");
        $peoples = $peopleCollection->find();
        $peopleArray = array();
        foreach($peoples as $key => $people) {
            array_push($peopleArray, $people);
        }
        echo json_encode(array("code" => 6200, "data" => $peopleArray));
    } catch(MongoConnectionException $e) {
        echo json_encode(array("code" => 6400));
    }
}